﻿import { BACKEND_HOST_LOCAL, BACKEND_HOST_PROD } from '@/constants';
import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import Swal from "sweetalert2";

// 与后端约定的响应数据格式
interface ResponseStructure {
  success: boolean;
  data: any;
  errorCode?: number;
  errorMessage?: string;
}

document.addEventListener("DOMContentLoaded", function () {

  function getNotificationVoUsingGet(params) {
    const url = `http://localhost:7529/api/notification/get/vo`;
    // const url = `${BACKEND_HOST_PROD}/api/notification/get/vo`;

    return fetch(url + "?" + new URLSearchParams(params))
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => data)
      .catch((error) => {
        // 处理错误
        console.error("Fetch request error:", error);
        throw error;
      });
  }

  const fetchNotification = function (domain) {
    // 发起请求获取通知信息的逻辑
    getNotificationVoUsingGet({ domain })
      .then((response) => {
        const data = response.data;
        const id = data.id;
        const updateTime = data.updateTime;
        if (
          !localStorage.getItem(id + updateTime) &&
          data.title &&
          data.content
        ) {
          // 使用 SweetAlert2 显示弹窗
          Swal.fire({
            title: data.title,
            text: data.content,
            icon: "info",
            confirmButtonText: "知道了",
          });

          // 存储到 localStorage
          localStorage.setItem(id + updateTime, "id");
        }
      })
      .catch((error) => {
        console.error("Fetch request error:", error);
      });
  };

  const url = new URL(location.href);
  const domain = url.hostname;
  fetchNotification(domain);
});

const isDev = process.env.NODE_ENV === 'development';

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const requestConfig: RequestConfig = {
  baseURL: isDev ? BACKEND_HOST_LOCAL : BACKEND_HOST_PROD,
  withCredentials: true,

  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      // 拦截请求配置，进行个性化处理。
      return config;
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 请求地址
      const requestPath: string = response.config.url ?? '';

      // 响应
      const { data } = response as unknown as ResponseStructure;
      if (!data) {
        throw new Error('服务异常');
      }

      // 错误码处理
      const code: number = data.code;
      // 未登录，且不为获取用户登录信息接口
      if (
        code === 40100 &&
        !requestPath.includes('user/get/login') &&
        !location.pathname.includes('/user/login')
      ) {
        // 跳转至登录页
        window.location.href = `/user/login?redirect=${window.location.href}`;
        throw new Error('请先登录');
      }

      if (code !== 0) {
        throw new Error(data.message ?? '服务器错误');
      }
      return response;
    },
  ],
};
